const jwt = require('jsonwebtoken');
const { User } = require('../models');
const bcrypt = require('bcryptjs');
const { DietRecord } = require('../models');
const { Op } = require('sequelize');

// 计算BMI
function calculateBMI(weight, height) {
  const heightInMeters = height / 100;
  return (weight / (heightInMeters * heightInMeters)).toFixed(1);
}

// 计算基础代谢率(BMR)
function calculateBMR(weight, height, age, gender) {
  if (gender === 'male') {
    return 66 + (13.7 * weight) + (5 * height) - (6.8 * age);
  } else {
    return 655 + (9.6 * weight) + (1.8 * height) - (4.7 * age);
  }
}

// 获取推荐类型
function getRecommendationType(bmi) {
  if (bmi < 18.5) {
    return '偏瘦';
  } else if (bmi >= 18.5 && bmi < 24) {
    return '正常';
  } else if (bmi >= 24 && bmi < 28) {
    return '超重';
  } else {
    return '肥胖';
  }
}

// 生成健康建议
function generateHealthSuggestions(bmi) {
  let suggestions = [];
  
  if (bmi < 18.5) {
    suggestions = [
      '适当增加饮食摄入量',
      '注意营养均衡，多摄入优质蛋白',
      '进行适度的力量训练',
      '保证充足的休息和睡眠'
    ];
  } else if (bmi >= 18.5 && bmi < 24) {
    suggestions = [
      '继续保持健康的生活方式',
      '定期进行体育锻炼',
      '保持均衡饮食',
      '注意作息规律'
    ];
  } else if (bmi >= 24 && bmi < 28) {
    suggestions = [
      '控制饮食摄入量',
      '增加有氧运动时间',
      '减少高热量食物摄入',
      '保持规律作息'
    ];
  } else {
    suggestions = [
      '严格控制饮食摄入',
      '每天进行有氧运动',
      '避免高热量、高脂肪食物',
      '建议咨询专业医生'
    ];
  }
  
  return suggestions;
}

const userController = {
  // 获取用户列表
  async getUsers(req, res) {
    try {
      const users = await User.findAll({
        attributes: { exclude: ['password'] }
      });
      res.json(users);
    } catch (error) {
      console.error('获取用户列表失败:', error);
      res.status(500).json({ message: '获取用户列表失败' });
    }
  },

  // 用户注册
  async register(req, res) {
    try {
      const { 
        username, 
        password, 
        nickname,
        gender,
        age,
        height,
        weight,
        goal,
        dietaryRestrictions 
      } = req.body;

      // 检查用户名是否已存在
      const existingUser = await User.findOne({ where: { username } });
      if (existingUser) {
        return res.status(400).json({ message: '用户名已存在' });
      }

      // 创建新用户
      const user = await User.create({
        username,
        password,
        nickname,
        gender,
        age,
        height,
        weight,
        goal,
        dietaryRestrictions
      });

      // 生成JWT token
      const token = jwt.sign(
        { id: user.id },
        process.env.JWT_SECRET,
        { expiresIn: '7d' }
      );

      res.json({
        token,
        user: {
          id: user.id,
          username: user.username,
          nickname: user.nickname,
          gender: user.gender,
          age: user.age,
          height: user.height,
          weight: user.weight,
          goal: user.goal,
          dietaryRestrictions: user.dietaryRestrictions
        }
      });
    } catch (error) {
      console.error('注册失败:', error);
      res.status(500).json({ message: '注册失败' });
    }
  },

  // 用户登录
  async login(req, res) {
    try {
      const { username, password } = req.body;

      // 查找用户
      const user = await User.findOne({ where: { username } });
      if (!user) {
        return res.status(401).json({ message: '用户名或密码错误' });
      }

      // 验证密码
      const isValidPassword = await user.validatePassword(password);
      if (!isValidPassword) {
        return res.status(401).json({ message: '用户名或密码错误' });
      }

      // 生成JWT token
      const token = jwt.sign(
        { id: user.id },
        process.env.JWT_SECRET,
        { expiresIn: '7d' }
      );

      res.json({
        token,
        user: {
          id: user.id,
          username: user.username,
          nickname: user.nickname,
          gender: user.gender,
          age: user.age,
          height: user.height,
          weight: user.weight,
          goal: user.goal,
          dietaryRestrictions: user.dietaryRestrictions
        }
      });
    } catch (error) {
      console.error('登录失败:', error);
      res.status(500).json({ message: '登录失败' });
    }
  },

  // 获取用户信息
  async getProfile(req, res) {
    try {
      const user = await User.findByPk(req.user.id);
      res.json({
        id: user.id,
        username: user.username,
        avatar: user.avatar,
        nickname: user.nickname,
        gender: user.gender,
        age: user.age,
        height: user.height,
        weight: user.weight,
        goal: user.goal,
        dietaryRestrictions: user.dietaryRestrictions
      });
    } catch (error) {
      console.error('获取用户信息失败:', error);
      res.status(500).json({ message: '获取用户信息失败' });
    }
  },

  // 更新用户信息
  async updateProfile(req, res) {
    try {
      const { 
        nickname,
        gender,
        avatar,
        age,
        height,
        weight,
        goal,
        dietaryRestrictions 
      } = req.body;

      await User.update({
        nickname,
        gender,
        avatar,
        age,
        height,
        weight,
        goal,
        dietaryRestrictions
      }, {
        where: { id: req.user.id }
      });

      // 获取更新后的用户信息
      const updatedUser = await User.findByPk(req.user.id);
      res.json({
        id: updatedUser.id,
        username: updatedUser.username,
        avatar: updatedUser.avatar,
        nickname: updatedUser.nickname,
        gender: updatedUser.gender,
        age: updatedUser.age,
        height: updatedUser.height,
        weight: updatedUser.weight,
        goal: updatedUser.goal,
        dietaryRestrictions: updatedUser.dietaryRestrictions
      });
    } catch (error) {
      console.error('更新用户信息失败:', error);
      res.status(500).json({ message: '更新用户信息失败' });
    }
  },

  // 删除用户
  async deleteUser(req, res) {
    try {
      await User.destroy({
        where: { id: req.params.id }
      });

      res.json({ message: '删除成功' });
    } catch (error) {
      console.error('删除用户失败:', error);
      res.status(500).json({ message: '删除用户失败' });
    }
  },

  // 获取健康分析
  async getHealthAnalysis(req, res) {
    try {
      const user = await User.findByPk(req.user.id);
      if (!user.height || !user.weight) {
        return res.status(400).json({ message: '请先完善身高体重信息' });
      }

      const bmi = calculateBMI(user.weight, user.height);
      const bmr = calculateBMR(user.weight, user.height, user.age, user.gender);
      const dailyCalories = Math.round(bmr * 1.2); // 假设轻度活动水平
      const recommendationType = getRecommendationType(bmi);
      const suggestions = generateHealthSuggestions(bmi);

      res.json({
        bmi,
        bmr,
        dailyCalories,
        recommendationType,
        suggestions
      });
    } catch (error) {
      console.error('获取健康分析失败:', error);
      res.status(500).json({ message: '获取健康分析失败' });
    }
  }
};

module.exports = userController; 